const WebSocket = require('ws');

const ws = new WebSocket.Server({port: 18081});

let scanEquipmentMsg = {
    scanEquipment_PlcPnStatus: [true, false, true, false, true, false, true, false, true, false, true, false],
    scanEquipment_PlcErrStatus: [0, 1, 2, 3, 3, 2, 1, 0, 3, 2, 1, 0],
    scanEquipment_PlcRealTimeStatus: [17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17],
};

ws.on('connection', ws => {
    console.log('WebSocket connection established.');

    ws.on('message', message => {
        console.log('Received:', message);
    });

    setInterval(() => {
        // 模拟更改数据
        scanEquipmentMsg.scanEquipment_PlcPnStatus = scanEquipmentMsg.scanEquipment_PlcPnStatus.map(status => !status);
        scanEquipmentMsg.scanEquipment_PlcErrStatus = scanEquipmentMsg.scanEquipment_PlcErrStatus.map(status => (status + 1) % 4);
        scanEquipmentMsg.scanEquipment_PlcRealTimeStatus = scanEquipmentMsg.scanEquipment_PlcRealTimeStatus.map(status => (status + 1) % 2);

        const keys = Object.keys(scanEquipmentMsg);
        const randomKey = keys[Math.floor(Math.random() * keys.length)];
        const randomData = {[randomKey]: scanEquipmentMsg[randomKey]};

        ws.send(JSON.stringify({scanEquipmentMsg: randomData}));
    }, 1000);
});

ws.on('close', () => {
    console.log('WebSocket connection closed.');
});
